<template>
  <div class="home">
    <div v-if="class_mode=='PAD_SINGLE'" @click="exitRoom" class="home-back">
      <img src="~assets/home/logout-icon.png" />退出
    </div>
    <div class="home-title">
      学习中心
    </div>
    <router-link to="/setting" class="home-setting">
      <img src="~assets/home/setting.png" alt="" />
    </router-link>
    <div class="home-content">
      <!-- <div v-if="!doubleminus || doubleminus == 0">
        <router-link v-for="(router, index) in courseList" :key="`router-${router.question_type}`" :id="`yxp:homeNav${index}`" :to="routerMap[router.question_type + '']" class="title-item synclock">
          <span>{{router.title}}</span>
        </router-link>
      </div> -->
      <div class="home-content">
        <div
                v-for="router in courseList.course"
                :key="router.id"
                :id="`yxp_homeNav${router.question_type}`"
                class="title-item_double synclock_double"
                @click="handleSelectLexicon(router.id,router.level_title,router.question_type,router.last_chapter,router.last_chapter_name,router.last_essay_unit,router.course_type,router.has_result,router.is_expire,router.can_study,router.postpaid)"
        >
          <span class="course_title">{{router.level_title}}</span><br/>
          <!-- <span class="course_expire green" v-if="!router.is_expire">有效期：{{router.expire_time}}</span> -->
          <!-- <span class="course_expire red" v-else>有效期：{{router.expire_time}}</span> -->
        </div>
      </div>
    </div>
    <div class="mark" v-if="isShow || isreFresh"></div>
    <div class="yxp-word-pop" v-if="isShow">
      <img src="@/assets/word/download-icon.png" class="downLoad"/>
      <p class="tips">正在导入单词包，请稍后（{{time}}s）…</p>
    </div>

    <div class="yxp-word-check" v-if="isreFresh">
      <img src="@/assets/word/word-check.png" class="check"/>
      <p class="tips font-20">{{detail}}</p>
      <div>
        <input type="password" class="ant-input" maxlength="12" id="login_pwd" name="login_pwd" placeholder="请输入登录密码" v-model="password">
      </div>
      <div class="btn">
        <div class="btn-item1 bg-warn" @click="handleOK" id="yxp-index-ok">确定</div>
        <div class="btn-item1" @click="handleCancle" id="yxp-index-cancle">取消</div>
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>

<script>
// @ is an alias to /src
import { fetchCourse ,fetchdoubleCourse} from "@/services/home";
import { SUCCESS_CODE } from "@/utils/const";
import {getQueryString} from '@/utils/tools'
import Timetips from '@/components/Timetips.vue'
import { mapState, mapMutations } from "vuex";
import { checkisnow ,checkHasword ,refreshword} from '@/services/word.js'

export default {
  name: "Home",
  components: {
    Timetips
  },
  data() {
    return {
      class_mode: '',
      courseList: [],
      doubleminus:0,
      postpaid:0,
      isreFresh:false,
      isShow:false,
      time: 10,
      timer1: null,
      timer2: null,
      lastpackageid:0,
      lastpackagetitle:'',
      detail:'',
      has_result:0,
      is_doubleminus:sessionStorage.getItem('doubleminus_type'),
      routerMap:{
        "0": '/wordRemember',
        "1": '/super-read',
        "3": '/reverse',
        "4": '/composition'
      },
      routerMap1:{
        "0": '/wordRemember',
        "1": '/super-read/doubleminusindex',
        "3": '/reverse',
        "4": '/composition'
      }
    };
  },
  computed: {},
  methods: {
    ...mapMutations(['changeWorkTime','setAfterOutTime']),
    // 单词包导入
    async getWordCheck (id,title) {
      let data = await checkHasword({ package_id: id })
      if (data.code === 1) {
        if (data.data.type === 10001) {
          clearInterval(this.timer)
          clearInterval(this.timer2)
          this.isShow = false
          // if(this.doubleminus == 1){
          //   this.checkisnow(id,title)
          // }else {
            this.$router.push({
              path: '/wordRemember',
              query: {
                package_id: id,
                title: title
              }
            })
          // }
        }
      } else if (data.code === '10001' || data.code === 10001) {
        // this.$loading.hide()
        this.$toast('token过期，请重新登录')
      } else {
        // this.$loading.hide()
        this.$toast(data.info)
      }
    },
    exitRoom () {
      if(this.doubleminus){
        window.location.href = `${window.location.href.replace(new RegExp('pad/index.html.+$'), 'index.html')}#/`
      }else {
        window.location.href = `${window.location.href.replace(new RegExp('pad/index.html.+$'), 'index.html')}#/mycourse`
      }
    },
    func(event) {
      let { cmd, msg } = event.data;
      if (cmd === "open") {
        this.$router.push("/room");
        console.log(msg);
      }
    },
    // 开始学习
    handleSelectLexicon (_id,_title,_question_type,_chapter,_chapter_name,_last_unit,course_type,has_result,is_expire,can_study,postpaid) {
           this.has_result = has_result
           if(is_expire){
                   this.$toast('该课程已过期，请续费后操作');return false;
           }
           if(!can_study){
                   this.$toast('该课程受服务中心控制，暂时无法学习，请联系老师确认');return false;
           }           
           sessionStorage.setItem('postpaid',postpaid);
      let _query = {
        package_id: _id,
        title:_title
      };
      if(_question_type == 3){//语法
        _query = {
          curr_id: _id,//课程id
          chapters_id: _chapter,//章节di
          name:_chapter_name,//章节标题
          pack_name:_title//课程标题
        }
      }
           
      if(_question_type == 4){//写作
        _query = {
          curr_id: _id,//课程id
          last_unit: _last_unit,//上次学习单元信息di
          pack_name:_title,//课程标题
          course_type:course_type
        }
           sessionStorage.setItem('essay_course_course_type',course_type);
           sessionStorage.setItem('essay_course_title',_title);
           sessionStorage.setItem('essay_course_id',_id);
      }
      if(_question_type > 0){
        this.$router.push({
          path: this.routerMap1[_question_type],
          query: _query
        })
      }else{
             if(this.is_doubleminus == 2 || this.is_doubleminus == 3){
               this.checkisnow(_id,_title)
             }else{
                   //单词校验是否已导入
                   this.export_words(_id,_title,has_result)
             }
      }
    },
	async export_words(_id,_title,has_result){
           if(has_result){
                this.$router.replace({
                path: '/wordRemember',
                query: {
                package_id: _id,
                title: _title
                }
            })
           }else {
             this.isShow = true
             this.getWordCheck(_id,_title)
             this.timer1 = setInterval(() => {
                   this.time--
                   if (this.time === 0) this.time = 10
             }, 1000)
             this.timer2 = setInterval(() => {
                   this.getWordCheck(_id,_title)
             }, 5000)
           }
	},
	async checkisnow (_id,_level_title){
      let data = await checkisnow({ package_id: _id })
      if(data.code == 1){
        if(data.data.id > 0){
          //提示清空记录
          this.isreFresh = true
          this.detail = '您正在切换到新课程，继续操作将导致当前课程记录清零，请慎重！！！';
          this.lastpackageid = _id
          this.lastpackagetitle = _level_title
        }else{
          this.export_words(_id,_level_title,this.has_result)
        }
      }
    },
    //确定重置记录
    async handleOK (){
      //清空记录
      let _login_pwd = document.getElementById("login_pwd").value;
      let data = await refreshword({ pwd:_login_pwd })
      if(data.code == 1){
             this.export_words(this.lastpackageid,this.lastpackagetitle,this.has_result)
      }else{
        this.$toast(data.info)
      }
    },
    //不重置记录
    handleCancle (){
      this.isreFresh = false
    },
  },
  created() {
    this.class_mode = getQueryString('class_mode') || 'PAD_121'
    let room_id = getQueryString("room_id");
    this.doubleminus = getQueryString("doubleminus");
    this.after_out_time = getQueryString("after_out_time");
    this.work_end_time = getQueryString("work_end_time");
    // this.doubleminus = 1;
    // console.log(this.doubleminus);
    // room_id = '928657261680416513234392865'
    sessionStorage.setItem('doubleminus_type',this.doubleminus);
    // this.changeWorkTime(this.work_end_time)
    // this.work_end_time = 10
    // this.after_out_time = 600
    this.timecountdown = sessionStorage.setItem('work_end_time',this.work_end_time)
    this.canAloneTime = sessionStorage.setItem('after_out_time_min',Number(this.after_out_time/60))
    this.end_time = sessionStorage.setItem('after_out_time_sec',this.after_out_time)
    if (room_id) {
      // fetchCourse({
      //   class_num: room_id,
      // }).then((res) => {
      //   if (res.code === SUCCESS_CODE) {
      //     this.courseList = res.data;
      //     console.log('course',this.courseList);
      //   }
      // });
           fetchdoubleCourse({
                   class_num: room_id,
           }).then((res) => {
                   console.log('----------------');
                   console.log('result:',res);
                   if (res.code === 1) {
                     this.courseList = res.data;
                   }else{
                     this.exitRoom();
                   }
           });
    }else {
      if (this.doubleminus) {
        fetchdoubleCourse({
        }).then((res) => {
          console.log('result:',res);
          if (res.code === 1) {
            this.courseList = res.data;
          }else{                   
                   this.exitRoom();
                   }
        });
      }
    }
  },
  mounted() {},
  
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less" scope>
.home {
  height: 100%;
  min-height: 700px;
  background-image: url("~assets/home/bg2.png");
  background-repeat: repeat-y;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  &-back {
    position: absolute;
    left: 30px;
    top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 110px;
    height: 50px;
    font-size: 20px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    line-height: 26px;
    color: #606B7B;
    background: #fff;
    border-radius: 10px;
    cursor: pointer;
    img {
      width: 20px;
      height: 20px;
      margin-right: 5px;
    }
  }
  .home-content {
    max-height: 600px;
    overflow: auto;
    .title-item {
      display: block;
      width: 800px;
      height: 140px;
      background-size: 100% 100%;
      line-height: 140px;
      color: #114139;
      font-weight: 700;
      font-size: 34px;
      margin-bottom: 30px;
      &:nth-of-type(1) {
        background-image: url("~assets/home/title1.png");
      }
      &:nth-of-type(2) {
        background-image: url("~assets/home/title2.png");
      }
      &:nth-of-type(3) {
        background-image: url("~assets/home/title3.png");
      }
      &:nth-of-type(4) {
        background-image: url("~assets/home/title4.png");
      }
    }
	.synclock_double{
           position:relative;
           .course_title{
                   position: absolute;
                   left: 100px;
           }
           .course_expire{
                   position: absolute;
                   right: 80px;
                   top: 30px;
                   font-size: 15px;
           }
           .green{
                   color: green;
           }
           .red{
                   color: red;
           }
	}
  }
  .home-content {
    .title-item_double {
      display: block;
      width: 800px;
      height: 140px;
      background-size: 100% 100%;
      line-height: 140px;
      color: #114139;
      font-weight: 700;
      font-size: 34px;
      margin-bottom: 30px;
    }
    #yxp_homeNav0 {
      background-image: url("~assets/home/title2.png");
    }
    #yxp_homeNav1 {
      background-image: url("~assets/home/title1.png");
    }
    #yxp_homeNav3 {
      background-image: url("~assets/home/title3.png");
    }
    #yxp_homeNav4 {
      background-image: url("~assets/home/title4.png");
    }
  }
  .home-setting {
    position: absolute;
    width: 50px;
    height: 50px;
    border-radius: 10px; /* no */
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    top: 20px; /* no */
    right: 20px; /* no */
    img {
      width: 20px;
    }
  }
  .home-title {
    position: absolute;
    width: 100px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 20px; /* no */
    font-size: 20px;
  }

}
.font-20{
  font-size: 20px!important;
}
.bg-warn{
  background-color: #F3B502!important;
}
.yxp-word-check {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 330px;
  height: 398px;
  text-align: center;
  background: #fff;
  border-radius: 10px;
  padding-left: 15px;
  padding-right: 15px;
  z-index: 1000;
  .close {
    position: absolute;
    right: 20px;
    top: 20px;
    width: 20px;
    height: 20px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .check {
    display: inline-block;
    width: 150px;
    height: 150px;
    margin: 25px auto 0;
  }
  .tips {
    font-size: 24px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
  }
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 30px auto 0;
    &-item {
      width: 280px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background: #27BFA3;
      border-radius: 100px;
      cursor: pointer;
      &:hover {
        background: #18A38A;
      }
    }
    &-item1 {
      width: 130px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background: #27BFA3;
      border-radius: 100px;
      cursor: pointer;
      &:first-child {
        margin-right: 15px;
      }
      &:hover {
        background: #18A38A;
      }
    }
  }
}

.yxp-word-pop {
  position: fixed;
  left:50%;
  top: 50%;
  transform: translate(-55%,-50%);
  width: 600px;
  height: 400px;
  text-align: center;
  background: #fff;
  border-radius: 10px;
  z-index: 1200;
  .downLoad {
    display: block;
    width: 134px;
    height: 160px;
    margin: 94px auto 14px;
  }
  .tips {
    font-size: 24px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    line-height: 30px;
  }
}
</style>
